package com.bihua.web.controller.blog;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bihua.blog.domain.BlogUser;
import com.bihua.blog.domain.bo.BlogUserBo;
import com.bihua.blog.domain.vo.BlogUserVo;
import com.bihua.blog.service.IBlogUserService;
import com.bihua.common.annotation.Log;
import com.bihua.common.annotation.RepeatSubmit;
import com.bihua.common.core.controller.BaseController;
import com.bihua.common.core.domain.R;
import com.bihua.common.core.validate.EditGroup;
import com.bihua.common.enums.BusinessType;
import com.bihua.common.helper.LoginHelper;
import com.bihua.common.utils.StringUtils;
import com.bihua.common.utils.file.MimeTypeUtils;
import com.bihua.system.domain.vo.SysOssVo;
import com.bihua.system.service.ISysOssService;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.io.FileUtil;
import lombok.RequiredArgsConstructor;

/**
 * 用户信息
 *
 * @author bihua
 * @date 2023-05-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/blog/blogUser")
public class BlogUserController extends BaseController {

    private final IBlogUserService iBlogUserService;
    private final ISysOssService iSysOssService;
    /**
     * 获取用户信息详细信息
     */
    @GetMapping("/getInfo")
    public R<BlogUserVo> getInfo() {
        return R.ok(iBlogUserService.queryById(getUserId()));
    }
    /**
     * 修改用户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BlogUserBo bo) {
        return toAjax(iBlogUserService.updateByBo(bo));
    }
   /**
     * 重置密码
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R<Void> resetPwd(@RequestBody BlogUser user) {
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        return toAjax(iBlogUserService.resetPwd(user));
    }
    /**
     * 修改密码
     *
     * @param newPassword 旧密码
     * @param oldPassword 新密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public R<Void> updatePwd(String oldPassword, String newPassword) {
        BlogUserVo user = iBlogUserService.queryById(LoginHelper.getUserId());
        String userName = user.getUserName();
        String password = user.getPassword();
        if (!BCrypt.checkpw(oldPassword, password)) {
            return R.fail("修改密码失败，旧密码错误");
        }
        if (BCrypt.checkpw(newPassword, password)) {
            return R.fail("新密码不能与旧密码相同");
        }

        if (iBlogUserService.resetUserPwd(userName, BCrypt.hashpw(newPassword)) > 0) {
            return R.ok();
        }
        return R.fail("修改密码异常，请联系管理员");
    }
    /**
     * 头像上传
     *
     * @param avatarfile 用户头像
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, Object>> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
        Map<String, Object> ajax = new HashMap<>();
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            SysOssVo oss = iSysOssService.upload(avatarfile);
            String avatar = oss.getUrl();
            if (iBlogUserService.updateUserAvatar(getUsername(), avatar)) {
                ajax.put("imgUrl", avatar);
                return R.ok(ajax);
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }

    @PostMapping(value = "/test", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SaIgnore
    public R materialFileUpload(String fileName, String mediaType) throws IOException {
        return R.fail("文件不得为空");
    }
}
